package main

import (
	"fmt"
	"github.com/robfig/cron/v3"
	_ "jkrb_v2.0/init"
	config "jkrb_v2.0/init"
	"jkrb_v2.0/mail"
	"jkrb_v2.0/module"
	"jkrb_v2.0/post"
	"log"
	"time"
)

func init() {
	module.GetConnect()
}

var User []module.UserDesc

func main() {
	c := cron.New()
	c.AddFunc(config.ConfigA.Minites+" "+config.ConfigA.Time+" * * *", func() {
		dailyPost()
	})
	c.Start()
	fmt.Println("服务开启成功")
	select {}
}

func getUser() []module.UserDesc {
	var user []module.UserDesc
	module.Conn.Table("user_descs").Where("auth =?", 1).Scan(&user)
	return user
}

func isConn() (x bool) {
	user := module.UserDesc{
		UserName: "相博",
		Email:    "1015286189@qq.com",
		Auth:     1,
	}
	defer func() {
		if err := recover(); err != nil {
			mail.Send(user, "数据库连接断开。")
			x = false
		}
	}()
	err := module.Conn.DB().Ping()
	if err == nil {
		return true
	} else {
		mail.Send(user, "数据库连接断开")
		return false
	}
}

func dailyPost() {
	if isConn() {
		User = getUser()
	}
	for i := 0; i < len(User); i++ {
		j := 0
		for j < 5 {
			time.Sleep(time.Second * 3)
			if ok, msg := post.Post_Message(User[i]); ok {
				log.Println(User[i].UserName, msg)
				break
			} else if !ok && j == 4 {
				mail.Send(User[i], msg)
			}
			j++
		}
	}
}
